<template>
  <div class="Talent_pool">
    <div class="main">
      <!-- 招聘会预定 -->
      <div class="booking">招聘会预定</div>
      <div class="job_LocationSelection">
        <div class="booking_position">位置选择</div>
        <div class="job_selection">
          <el-scrollbar :native='false' wrapStyle="" wrapClass="" viewClass="" viewStyle="" :noresize="false"
            tag="section">
            <div class="select_Choice">
              <div class="job_seat_wai" :class="[{'job_seat_Selection' : job_seat_Selection_index == index}]"
                v-for="(item,index) in boothNum" :key="index" @click="job_seat(item, index)">
                <span class="job_seat"
                  :class="statusText[(item.auditStatus ||(item.auditStatus==0) && item.auditStatus >= 0) ? item.auditStatus : 2][0]">{{item.place}}</span>
                <!-- <span class="job_seat">{{item}}</span> -->
              </div>
            </div>
          </el-scrollbar>
          <div class="job_Explain">
            <div class="reservationPosition">
              <span>预约位置</span>
              <input type="text" v-model="PositionVal" readonly>
            </div>
            <div class="reservationStatus">
              <div>
                <span></span>
                可预约
              </div>
              <div>
                <span></span>
                预约审核中
              </div>
              <div>
                <span></span>
                已预约
              </div>
              <div>
                <span></span>
                预留不可预约
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 企业预定信息 -->
      <div class="job_LocationSelection">
        <div class="booking_position">企业预定信息</div>
        <div class="form" style="width:70%;margin:0 auto;">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
            <el-row>
              <el-col :span="12">
                <el-form-item label="企业名称：">
                  <el-input v-model="companybyuser.name" disabled></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="对外展示名称：" prop="shortName">
                  <el-input v-model="ruleForm.shortName" placeholder="对外展示名称"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="联系人：" prop="contact">
                  <el-input v-model="ruleForm.contact" v-if="!ruleForm.companyContact" placeholder="联系人"></el-input>
                  <el-input v-model="companybyuser.contact" v-else :disabled="ruleForm.companyContact"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <div class="enterprise">
                  <el-checkbox v-model="ruleForm.companyContact">企业联系人</el-checkbox>
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="联系方式：" prop="phone">
                  <!-- <el-input v-model="ruleForm.phone" :disabled="ruleForm.companyContact" placeholder="联系方式"></el-input> -->
                  <el-input v-model="ruleForm.phone" v-if="!ruleForm.companyContact" placeholder="联系方式"></el-input>
                  <el-input v-model="companybyuser.contactPhone" v-else :disabled="ruleForm.companyContact"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="联系人邮箱：" prop="mail">
                  <!-- <el-input v-model="ruleForm.mail" :disabled="ruleForm.companyContact" placeholder="联系人邮箱"></el-input> -->
                  <el-input v-model="ruleForm.mail" v-if="!ruleForm.companyContact" placeholder="联系人邮箱"></el-input>
                  <el-input v-model="companybyuser.contactMail" v-else :disabled="ruleForm.companyContact"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="18">
                <el-form-item label="公司福利：">
                  <p class="job_welfare">
                    <span class="welfare">增加公司标签，提升公司诱人指数 (最多可选择 8 个) </span> <span class="esitTag"
                      @click="esitTag"><img src="../../../assets/img/add_tag.png" alt=""> 修改标签</span>
                  </p>
                  <div class="tag-group">
                    <el-tag v-for="(item,index) in allure" :key="index" effect="plain">
                      {{ item.name }}
                    </el-tag>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="18">
                <el-form-item v-for="(domain, index) in domains" :label="'职位：' + Number(index+1)" :key="index">
                  <el-input v-model="domain.name" disabled="disabled" style="width:58%;"></el-input>
                  <el-button style="margin-left:30px;" size="mini" type="danger" plain
                    @click.prevent="removeDomain(domain)">删除</el-button>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="20">
                <el-form-item>
                  <el-button @click="addDomain" style="width:224px;display:flex;justify-content:center;">
                    <span class="esitTag"><img src="../../../assets/img/add_tag.png" alt=""> 添加职位</span>
                  </el-button>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item>
              <el-button style="width:148px; height:46px; margin-top:30px;" :loading="isloading" type="primary"
                size="medium" @click="submitForm('ruleForm')">确定</el-button>
              <el-button style="margin-left:50px;width:148px; height:46px;" type="primary" plain size="medium"
                @click="resetForm('ruleForm')">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <!-- 设置公司标签组件 -->
      <set-CompanyLabel ref="getListTag" :esitTagBoolean="esitTagBoolean" @close="close"
        @confirmHaveTag="confirmHaveTag" :allure="allure">
      </set-companyLabel>
      <!-- 选择职位组件 -->
      <job-selection ref="childClick" :jobSelectionBoolean="jobSelectionBoolean" :domains="domains"
        :companyId="ruleForm.companyId" @close="close" @handleSelection="handleSelection"></job-selection>
    </div>
  </div>
</template>

<script>
import { jobfairforword, addCompanyJobFairJob, selectcompanybyuserid, findCompanyByPlace } from '../../../api/jobfair';
// 自定义正则表达式
import { validPhone } from '../../../utils/common'

export default {
  name: 'jobfairBooking',
  components: {},
  data () {
    return {
      // 禁用多次点击
      isloading: false,
      // 选中索引
      job_seat_Selection_index: -1,
      // 对应不同状态 显示不同按钮 以及颜色
      statusText: {
        // 0: ['reviewProgress', '预约审核中'],
        // 1: ['Booked ', '已预约'],
        // 2: ['notAllowed', '预留不可预约'],
        // 3: ['Reservations', '可预约']
        //  空 和 2 代表与预约
        0: ['reviewProgress', '预约审核中'],
        1: ['Booked ', '已预约'],
        3: ['notAllowed', '预留不可预约'],
        2: ['Reservations', '可预约']
      },
      // 预约位置 place
      PositionVal: '',
      // 福利标签
      allure: [],
      ruleForm: {
        // 招聘会ID
        jobFairId: '',
        // 企业ID
        companyId: '1',
        // 企业名称
        name: '',
        // 企业对外名称
        shortName: '',
        // 预定位置
        place: '',
        // 公司福利标签
        allure: '',
        // 是否为企业联系人
        companyContact: false,
        // 联系人
        contact: '',
        // 联系方式
        phone: '',
        // 联系邮箱
        mail: '',
        // 操作人id
        opeId: '',
        // 职位信息
        idsInVo: []
      },
      // 下方表单
      rules: {
        shortName: [
          { required: true, message: '请输入对外展示名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        contact: [
          { required: true, message: '请输入联系人名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' }, //这里需要用到全局变量
          { message: '请输入正确的手机号', validator: validPhone, trigger: 'blur' }
        ],
        mail: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ]
      },
      // 添加职位
      domains: [],
      // 添加公司标签 显示隐藏
      esitTagBoolean: false,
      // 添加职位弹框显示隐藏
      jobSelectionBoolean: false,
      // 企业联系人
      companyContact: false,
      // 站台个数
      boothNum: 0,
      // 不可预约
      retainBooth: [],
      // 已进入页面请求的企业，名称
      companybyuser: {}
    }
  },
  methods: {
    // 选择座位
    job_seat (val, index) {
      if (val.auditStatus == 1 || val.auditStatus == 3 || val.auditStatus == 0) return
      this.job_seat_Selection_index = index
      this.PositionVal = val.place
      //   findCompanyByPlace(val.place).then((res) => {
      //     if (res.success) {
      //       console.log(res.data, '456456465465')
      //       // this.open(res.data)
      //     }
      //   })

    },
    open (Number) {
      this.$confirm(`当前展位已有${Number}家企业正在排队预约审核中，您可选择其他展位，如其他企业审核成功，将取消您的预约。`, '', {
        confirmButtonText: '继续预约',
        cancelButtonText: '看看别的',
        customClass: 'message-logout'
      }).then(() => {
        // this.$message({
        //     type: 'info',
        //     message: '继续预约!'
        // });
      }).catch(() => {
        // this.$message({
        //     type: 'success',
        //     message: '看看别的'
        // });          
      });
    },
    //删除域名
    removeDomain (item) {
      var index = this.domains.indexOf(item)
      if (index !== -1) {
        this.domains.splice(index, 1)
      }
    },
    //   添加职位
    addDomain () {
      this.jobSelectionBoolean = true
      // 调用字组建的方法
      this.$refs.childClick.getPage()
    },
    // 提交
    submitForm (formName) {
      let that = this
      that.isloading = true
      if (!that.PositionVal) {
        that.$message.error('请选择展位');
        that.isloading = false
        return false
      }
      if (!that.companybyuser.name) {
        that.$message.error('企业名称获取失败');
        that.isloading = false
        return false
      }
      that.$refs[formName].validate((valid) => {
        if (valid) {
          // 1、 企业标签 变为字符串 传递
          let allures = []
          if (that.allure) {
            that.allure.map(v => {
              allures.push(Number(v.val))
            })
          }
          that.ruleForm.allure = JSON.stringify(allures)    //.join(',')
          // 2、职位信息
          let retainBooth = []
          if (that.domains.length <= 0) {
            that.$message.error('至少选择一个职位才可以预定');
            that.isloading = false
            return false
          }
          if (that.domains) {
            that.domains.map(v => {
              retainBooth.push({ id: v.id })
            })
          }
          // 是否为企业联系人
          that.ruleForm.idsInVo = retainBooth

          // 新增 预约方式 写死，测试和产品已确定 2020/5/19
          that.ruleForm.reserveType = 1

          // 企业名称
          that.ruleForm.name = that.companybyuser.name

          // 企业id
          that.ruleForm.companyId = that.companybyuser.id
          // 选择展位号码
          that.ruleForm.place = that.PositionVal
          addCompanyJobFairJob(that.ruleForm).then(data => {
            // 对请求出来的数据进行逻辑处理
            if (data.success) {
              that.$message({
                message: '提交成功',
                type: 'success'
              });
              that.isloading = false
              that.$router.go(-1)
            }

            that.resetForm('ruleForm')
            console.log(data, '企业预定信息');
          }).catch(err => {
            console.log(err)
            that.isloading = false
            that.$message('数据返回错误')
          });
        } else {
          console.log('error submit!!');
          that.isloading = false
          return false;
        }
      });
    },
    // 取消 并且重置
    resetForm (formName) {
      this.isloading = false
      this.$refs[formName].resetFields();
    },
    // 添加标签
    esitTag () {
      this.$refs.getListTag.getListTag()
      this.esitTagBoolean = true
    },
    // 关闭弹框
    close (val) {
      this.esitTagBoolean = val
      this.jobSelectionBoolean = val
    },
    confirmHaveTag (valTag) {
      console.log(valTag)
      this.close(false)
      this.allure = valTag
    },
    handleSelection (selectArr) {
      console.log(selectArr, '78979879879898798')
      this.domains = this.domains.concat(selectArr)
    },
    // 招聘会预定 接口请求
    jobfairforword () {
      jobfairforword(this.$route.query.id).then(data => {
        // 对请求出来的数据进行逻辑处理
        console.log(data, 'jobfairforword 招聘会预定');
        if (data.success) {
          let datas = data.data
          // 站台个数
          // this.boothNum = datas.boothNum - 0 // 返回字符串 变为数字（隐式转换） 

          // 先获取到 预留不可预约 的数据
          let retainBoothArr = []
          if (datas.retainBooth) {
            let numberString = ''
            datas.retainBooth.split(',').map((v, i) => {
              // 判断每一项是否包含 “-”
              if (v.indexOf('-') != -1) {
                // 把中间数字循环出来
                for (var y = Number(v.split('-')[0]); y <= Number(v.split('-')[1]); y++) {
                  // 判断是否是最后一个 如果是 把“，”去掉
                  // if (y == Number(v.split('-')[1])) {
                  //   numberString += y
                  // } else {
                  numberString += y + ','
                  // }
                }
              } else {
                /**
                 * feat:
                 * 这里是不带 “-”的数据
                 * 判断是否是最后一个 如果是 把“，”去掉
                 * */
                // if (datas.retainBooth.split(',').length - 1 == i) {
                //   numberString += v
                // } else {
                numberString += v + ','
                // }
              }
            })
            // 去重
            numberString = Array.from(new Set(numberString.split(',')))
            numberString.map((v, i) => {
              let objList = {}
              // feat: 这里的V 是一个数字 有可能为 空
              if (v) {
                objList.auditStatus = 3
                objList.place = v - 0
                retainBoothArr.push(objList)
              }
            })
          }


          // 获取 总数展位 
          let allNum = datas.boothNum - 0
          // 创建站数位对象（个数）
          let allNumarr = Array(allNum).fill({})

          // 总站数位的 数组 （全部数据）
          let ReservationArr = []

          let newArr = [...datas.list, ...retainBoothArr]

          allNumarr.map((v, i) => {
            let obj = {}
            obj.auditStatus = 2,
              obj.place = i + 1 - 0
            ReservationArr.push(obj)
          })

          // 总站数位的 与（预留不可预约和当前约审核中和已预约 的数据） 去循环遍历 
          let array = []
          ReservationArr.forEach((i, index) => {
            let flag = false
            newArr.forEach((j, jdex) => {
              if (i.place == j.place) {
                flag = true
              }
            })
            if (!flag) {
              array.push(i)
            }
          })
          let sortArr = [...datas.list, ...retainBoothArr, ...array]
          // 对数据进行正序排序
          sortArr.sort(function (a, b) {
            return a.place - b.place;
          });
          this.boothNum = sortArr
          // console.log(this.boothNum, 'this.retainBooth')
        }
      }).catch(err => {
        this.$message('数据返回错误')
      });
    },

    // 已进入页面获取企业相关信息 （接口请求）
    selectcompanybyuserid () {
      let obj = {
        userId: ''
      }
      selectcompanybyuserid(obj).then(data => {
        // 对请求出来的数据进行逻辑处理
        console.log(data, 'jobfairforword 招聘会预定');
        if (data.success) {
          this.companybyuser = data.data
        } else {
          this.$message('数据返回错误')
        }
      })
    },
    getRouterData () {
      this.ruleForm.jobFairId = this.$route.query.id
      console.log('this.ruleForm.jobFairId', this.ruleForm.jobFairId)
    }
  },
  created () {
    // 招聘会预定 接口请求
    this.jobfairforword()
    // 已进入页面获取企业相关信息 （接口请求）
    this.selectcompanybyuserid()
    // 招聘会id
    this.getRouterData()
  },
  watch: {
    "ruleForm.companyContact": {
      handler (newValue, oldValue) {
        console.log(newValue, "监听是否选择位企业联系人做一些操作");
        let that = this
        if (newValue) {
          that.ruleForm.contact = that.companybyuser.name
          that.ruleForm.mail = that.companybyuser.contactMail
          that.ruleForm.phone = that.companybyuser.contactPhone
          console.log(that.ruleForm)
        } else {
          that.ruleForm.phone = ''
          that.ruleForm.mail = ''
          that.ruleForm.contact = ''
        }
      }
    }
  }
}
</script>

<style lang="css" scoped>
.Talent_pool {
    margin-top: 30px;
    width: 100%;
}
.Talent_pool .main {
    background: rgba(246, 246, 248, 1);
    width: 1200px;
    margin: 0 auto;
}
/* 招聘会预定-位置选择 */
.booking {
    height: 69px;
    line-height: 69px;
    text-align: left;
    text-indent: 45px;
    font-size: 20px;
    font-family: PingFang SC;
    font-weight: 600;
    color: rgba(34, 34, 34, 1);
    opacity: 1;
    border-bottom: 2px solid rgba(232, 232, 232, 1);
    background: rgba(255, 255, 255, 1);
}
.job_LocationSelection {
    width: 100%;
    /* height: 359px; */
    background: #ffffff;
}
.booking_position {
    height: 67px;
    line-height: 67px;
    text-align: left;
    text-indent: 45px;
    font-size: 14px;
    font-family: PingFang SC;
    font-weight: 500;
    color: rgba(34, 34, 34, 1);
    position: relative;
}
.booking_position:after {
    width: 28px;
    height: 2px;
    content: '';
    position: absolute;
    bottom: 22px;
    left: 44px;
    background: #1893fc;
}

.job_selection {
    /* height: 292px; */
    border: 2px solid rgba(248, 248, 248, 1);
    margin: 0 auto;
}
/* 解决自定义滚动条 x 轴显示问题 */
.el-scrollbar__wrap {
    overflow-x: hidden;
}
.select_Choice {
    max-height: 211px;
    width: calc(100% - 20px);
    justify-content: flex-start;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    padding-top: 17px;
    padding-left: 20px;
}
.job_Explain {
    height: 64px;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background: rgba(248, 248, 248, 1);
}
.reservationPosition {
    font-size: 14px;
    font-family: PingFang SC;
    font-weight: 400;
    line-height: 20px;
    color: rgba(85, 85, 85, 1);
}
.reservationPosition input {
    width: 64px;
    height: 40px;
    line-height: 40px;
    margin: 0 69px 0 18px;
    text-align: center;
    background: rgba(255, 255, 255, 1);
    border: 1px solid rgba(232, 232, 232, 1);
    opacity: 1;
}
.reservationStatus {
    display: flex;
}
.reservationStatus div {
    margin-right: 42px;
}
.reservationStatus div:nth-child(1) span {
    width: 16px;
    height: 16px;
    display: inline-block;
    background: rgba(21, 155, 62, 1);
    vertical-align: middle;
    opacity: 1;
    border-radius: 2px;
}
.reservationStatus div:nth-child(2) span {
    width: 16px;
    height: 16px;
    display: inline-block;
    background: #fca428;
    vertical-align: middle;
    opacity: 1;
    border-radius: 2px;
}
.reservationStatus div:nth-child(3) span {
    width: 16px;
    height: 16px;
    display: inline-block;
    background: #fd4e40;
    vertical-align: middle;
    opacity: 1;
    border-radius: 2px;
}
.reservationStatus div:nth-child(4) span {
    width: 16px;
    height: 16px;
    display: inline-block;
    background: #cccccc;
    vertical-align: middle;
    opacity: 1;
    border-radius: 2px;
}

.job_seat_Selection {
    width: 48px !important;
    height: 48px !important;
    border: 2px solid rgba(21, 155, 62, 1);
    margin: 13px 26.5px !important;
    border-radius: 6px;
    background: #ffffff;
}
.job_seat_wai {
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 17px 30.5px;
}
.job_seat {
    width: 44px;
    height: 44px;
    display: inline-block;
    text-align: center;
    line-height: 44px;
    background: rgba(204, 204, 204, 1);
    opacity: 1;
    cursor: pointer;
    border-radius: 6px;
}

.Reservations {
    background: #009b3e;
}
.reviewProgress {
    background: #fca418;
}

.Booked {
    background: #fd4e40;
}
.notAllowed {
    background: #cccccc;
}

/* 招聘会预定 */

.job_welfare {
    display: flex;
    align-items: center;
}
.welfare {
    font-size: 14px;
    font-family: PingFang SC;
    font-weight: 400;
    line-height: 20px;
    color: rgba(34, 34, 34, 1);
    margin-right: 16px;
    opacity: 1;
}
.esitTag {
    display: flex;
    align-items: center;
    cursor: pointer;
    color: #0093ff;
}
.esitTag img {
    width: 13px;
    height: 13px;
    margin-right: 3px;
}
.tag-group .el-tag {
    margin-right: 20px;
}

.enterprise {
    margin-left: 54px;
    margin-top: 11px;
}
</style>

<style>
.message-logout .el-message-box__btns {
    text-align: center !important;
}
.message-logout .el-message-box__header {
    padding: 30px 15px 10px;
}
.message-logout .el-message-box__content {
    border-top: 2px solid rgba(0, 147, 255, 1);
}
.message-logout .el-message-box__headerbtn .el-message-box__close {
    color: #1893fc;
}
</style>